﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using BusinessPlatform.Core.BusinessObject;
using BusinessPlatform.Core.BusinessObject.Properties;
using BusinessPlatform.Core.BusinessObject.BOParser;
using BusinessPlatform.Core.Database;
using BusinessPlatform.Core.Result;
using BusinessPlatform.Core.BusinesObjectType;

namespace BusinessPlatform.Core.EntityParser
{
    /// <summary>
    /// 对象实体解析器
    /// </summary>
    public class EntityParser
    {
        public EntityParser()
        {
            _BOFactory = new BusinessObjectFactory();
        }
        private BusinessObjectFactory _BOFactory;
        /// <summary>
        /// 对象工厂
        /// </summary>
        private BusinessObjectFactory BOFactory
        {
            get { return _BOFactory; }
        }
        #region 保存
        /// <summary>
        /// 增加状态
        /// </summary>
        /// <param name="EntityObject"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private IResult NewMode(IBusinessObjectBase EntityObject, IDatabase db)
        {
            IResultT<object> resultT = new Result<object>();
            IResult result = null;
            //权限业务单据类型处理单据字段值
            IObjectHandling handler = new ObjectHandling(EntityObject);
            handler.New(db);
            //获取业务对象的属性及字段信息
            var iPropertiesManager = (EntityObject as IBusinessObjectProperties).PropertiesManager;
            //数据门户
            DataPortal Portal = new DataPortal(db, iPropertiesManager, DataPortalType.INSERT);
            var SQL = Portal.GetQueryString();
            var dbParameters = Portal.GetDbParameters();
            var AffectRow = db.ExceuteNonQuery(SQL, dbParameters);
            #region 处理子对象
            IBOParser boParser = new BOParser(EntityObject);
            foreach (var item in boParser.Children)
            {
                foreach (var BOChild in item.Children)
                {
                    result = Save(BOChild, db);
                }
            }
            #endregion
            if (AffectRow > 0)
            {
                resultT.SetResultFlag(true);
                result = resultT;
            }
            return result;
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="EntityObject"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private IResult UpdateMode(IBusinessObjectBase EntityObject, IDatabase db)
        {
            IResultT<object> resultT = new Result<object>();
            IResult result = null;
            //权限业务单据类型处理单据字段值
            IObjectHandling handler = new ObjectHandling(EntityObject);
            handler.Update();
            //获取业务对象的属性及字段信息            
            var iPropertiesManager = (EntityObject as IBusinessObjectProperties).PropertiesManager;
            //数据门户
            DataPortal Portal = new DataPortal(db, iPropertiesManager, DataPortalType.DELETE);
            var SQL = Portal.GetQueryString();
            var dbParameters = Portal.GetDbParameters();
            var AffectRow = db.ExceuteNonQuery(SQL, dbParameters);//删除
            if (AffectRow <= 0)
            {
                resultT.SetResult(false, "对象更新失败");
                throw new Exception("对象更新失败");
            }
            Portal = new DataPortal(db, iPropertiesManager, DataPortalType.INSERT);
            SQL = Portal.GetQueryString();
            dbParameters = Portal.GetDbParameters();
            AffectRow = db.ExceuteNonQuery(SQL, dbParameters);//添加
            #region 处理子对象
            IBOParser boParser = new BOParser(EntityObject);
            foreach (var item in boParser.Children)
            {
                foreach (var BOChild in item.Children)
                {
                    result = Save(BOChild, db);
                }
            }
            #endregion
            if (AffectRow > 0)
            {
                resultT.SetResultFlag(true);
                result = resultT;
            }
            return result;
        }
        /// <summary>
        /// 删除状态
        /// </summary>
        /// <param name="EntityObject"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private IResult DeleteMode(IBusinessObjectBase EntityObject, IDatabase db)
        {
            IResultT<object> resultT = new Result<object>();
            IResult result = null;
            //数据门户
            var iPropertiesManager = (EntityObject as IBusinessObjectProperties).PropertiesManager;
            DataPortal Portal = new DataPortal(db, iPropertiesManager, DataPortalType.DELETE);
            var SQL = Portal.GetQueryString();
            var dbParameters = Portal.GetDbParameters();
            var AffectRow = db.ExceuteNonQuery(SQL, dbParameters);//删除
            if (AffectRow <= 0)
            {
                resultT.SetResult(false, "对象更新失败");
                throw new Exception("对象更新失败");
            }
            #region 处理子对象
            IBOParser boParser = new BOParser(EntityObject);
            foreach (var item in boParser.Children)
            {
                foreach (var BOChild in item.Children)
                {
                    result = Save(BOChild, db);
                }
            }
            #endregion
            if (AffectRow > 0)
            {
                resultT.SetResultFlag(true);
                result = resultT;
            }
            return result;
        }
        /// <summary>
        /// 源状态
        /// </summary>
        /// <param name="EntityObject"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private IResult OriginalMode(IBusinessObjectBase EntityObject, IDatabase db)
        {
            IResult result = null;
            #region 处理子对象
            IBOParser boParser = new BOParser(EntityObject);
            foreach (var item in boParser.Children)
            {
                foreach (var BOChild in item.Children)
                {
                    result = Save(BOChild, db);
                }
            }
            #endregion
            return result;
        }
        /// <summary>
        /// 业务对象保存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="EntityObject"></param>
        /// <returns></returns>
        public IResult Save<T>(T EntityObject) where T : IBusinessObjectBase
        {
            IDatabase db = null;
            try
            {
                //创建数据库实例
                db = DatabaseFactory.CreateDatabase();
                //开启事务
                db.BeginTransaction();
                //保存
                var result = Save(EntityObject, db);
                //提交事务
                db.EndTranscation(TransactionOptions.Commit);
                return result;
            }
            catch (Exception ex)
            {
                if (db != null) db.EndTranscation(TransactionOptions.Rollback);
                throw (ex);
            }
        }
        /// <summary>
        /// 业务对象保存
        /// </summary>
        /// <param name="EntityObject"></param>
        /// <param name="db"></param>
        /// <returns></returns>
        private IResult Save(IBusinessObjectBase EntityObject, IDatabase db)
        {
            IResult result = null;
            //获取业务对象的状态
            var entityStatus = EntityObject as IBusinessObjectStatus;
            switch (entityStatus.Status)
            {
                //添加状态
                case BusinessObjectStatusEnumType.NewMode:
                    result = NewMode(EntityObject, db);
                    break;
                //更新
                case BusinessObjectStatusEnumType.UpdateMode:
                    result = UpdateMode(EntityObject, db);
                    break;
                //逻辑删除状态
                case BusinessObjectStatusEnumType.LogicalDeleteMode:
                    break;
                //物料删除状态
                case BusinessObjectStatusEnumType.PhysicalDeleteMode:
                    result = DeleteMode(EntityObject, db);
                    break;
                //原始状态
                case BusinessObjectStatusEnumType.OriginalMode:
                    result = OriginalMode(EntityObject, db);
                    break;
            }
            return result;
        }
        #endregion
        #region 查找
        public Result<T> Search<T>() where T : IBusinessObjectBase
        {
            return Search<T>(null);
        }
        /// <summary>
        /// 按查询条件返回结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cri"></param>
        /// <returns></returns>
        public Result<T> Search<T>(Criteria.ICriteria cri) where T : IBusinessObjectBase
        {
            try
            {
                //返回对象结果集
                IResultT<T> resultT = new Result<T>();
                Result<T> result = null;
                Type entityType = typeof(T);
                var BOresult = Search(cri, entityType);
                if (BOresult.ResultFlag)
                {
                    foreach (var entityObject in BOresult.BusinessObject)
                    {
                        var BO = entityObject as IBusinessObjectBase;
                        BOParser Parser = new BOParser(BO);
                        foreach (var item in Parser.Children)
                        {
                            entityType = item.ChildType;
                            //子对象的查询条件
                            cri = item.Criteria;
                            var childresult = Search(cri, entityType);
                            foreach (var childEntityObject in childresult.BusinessObject)
                            {
                                item.BOList.Add(childEntityObject);
                            }
                        }
                    }
                    foreach (var item in BOresult.BusinessObject)
                    {
                        resultT.BusinessObject.Add((T)item);
                    }
                    if (BOresult.ResultFlag)
                        resultT.SetResultFlag(true);
                }
                result = resultT as Result<T>;
                return result;
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
        /// <summary>
        /// 查找
        /// </summary>
        /// <param name="cri"></param>
        /// <param name="entityType"></param>
        /// <returns></returns>
        private IResult Search(Criteria.ICriteria cri, Type entityType)
        {
            //返回对象结果集
            IResultT<object> result = new Result<object>();
            //对象实例
            object BOInstance = BOFactory.CreateInstance(entityType); //Activator.CreateInstance(entityType);
            var Properties = (BOInstance as IBusinessObjectProperties).PropertiesManager;//获取属性

            IDatabase db = DatabaseFactory.CreateDatabase();//创建db对象            
            //数据门户
            DataPortal Portal = new DataPortal(db, Properties, cri);
            var SQL = Portal.GetQueryString();
            var dbParameters = Portal.GetDbParameters();

            //获取参数列表
            var DataReader = db.ExceuteReader(SQL, dbParameters);
            while (DataReader.Read())
            {
                object entity = BOFactory.CreateInstance(entityType); //Activator.CreateInstance(entityType);
                var entityProperties = (entity as IBusinessObjectProperties).PropertiesManager;
                DataPortal.FillData(entityProperties, DataReader);
                (entity as IBusinessObjectStatus).Status = BusinessObjectStatusEnumType.OriginalMode;
                result.BusinessObject.Add(entity);
                result.SetResultFlag(true);
            }
            DataReader.Close();
            DataReader.Dispose();
            db.CloseConnection();
            return result;
        }
        #endregion
    }
}
